package com.zlx.mall.basic.web.configuration;


import com.zlx.mall.basic.trace.MDCUtil;
import com.zlx.mall.basic.web.constant.TraceConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qingke
 **/
@Configuration
public class TraceRestTemplateConfiguration {

    @Bean("traceRestTemplate")
    public RestTemplate traceRestTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 10s
        // socket的建立时间 throws java.net.SocketTimeoutException
        requestFactory.setConnectTimeout(10 * 1000);
        requestFactory.setReadTimeout(10 * 1000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setInterceptors(createTraceInterceptors());

        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        for (int i = 0; i < messageConverters.size(); i++) {
            HttpMessageConverter<?> httpMessageConverter = messageConverters.get(i);
            if (httpMessageConverter.getClass().equals(StringHttpMessageConverter.class)) {
                messageConverters.set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            }
        }
        return restTemplate;
    }

    private List<ClientHttpRequestInterceptor> createTraceInterceptors() {
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
        interceptors.add(createTraceInterceptor());
        return interceptors;
    }

    private ClientHttpRequestInterceptor createTraceInterceptor() {
        return (request, body, execution) -> {
            HttpHeaders headers = request.getHeaders();
            headers.add(TraceConstants.HTTP_HEADER_TRACE_ID, MDCUtil.getOrCreateTraceId());
            return execution.execute(request, body);
        };
    }
}
